<?php
// 公共助手函数


if (!function_exists('datetime')) {
    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}


if (!function_exists('rmdirs')) {
    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }

}


if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }

}


if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
//            $info = parse_url($_SERVER['HTTP_ORIGIN']);
//            $configInfo = \app\admin\model\SysConfig::get(1);
//            $configInfo = json_decode($configInfo['according'], true);
            //该字段为空则代表所有域名均允许通过

//            if ($configInfo['allow_cross_domain'] != '*') {
//                $domainArr = explode(',', $configInfo['allow_cross_domain']);
//                if (is_array($domainArr)) {
//                    //去除两侧多余字符
//                    foreach ($domainArr as $key => $value) {
//                        $value = trim($value);
//                        $value = str_replace('http://', '', $value);
//                        $value = str_replace('https://', '', $value);
//                        $domainArr[$key] = $value;
//                    }
//                    if (in_array($info['host'], $domainArr)) {
//                        header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
//                    } else {
//                        header('HTTP/1.1 403 Forbidden');
//                        exit;
//                    }
//                }
//            }
//            header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);

            //TODO 测试阶段关闭跨域
            header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');
            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                exit;
            }
        }
    }
}


if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
//        $configInfo = \app\admin\model\SysConfig::get(1);
//        $configInfo = json_decode($configInfo['according'], true);
//        //该字段为空则代表所有ip均允许通过
//        if (empty($configInfo['forbidden_ip'])) {
//            return true;
//        }
//        $forbiddenIps = explode(',', $configInfo['forbidden_ip']);
        $forbiddenIps = \app\admin\model\SysForbiddenIp::field('ip')
            ->where([
                'status' => 1,
                'is_del' => 0
            ])
            ->select()
            ->toArray();
        $forbiddenIps = array_column($forbiddenIps, 'ip');
        if (in_array($ip, $forbiddenIps)) {
            return true;
        }
//        if (is_array($forbiddenIps)) {
//            //去除两侧多余字符
//            foreach ($forbiddenIps as $key => $value) {
//                $forbiddenIps[$key] = trim($value);
//            }
//            if (in_array($ip, $forbiddenIps)) {
//                return true;
//            }
//        }
        header('HTTP/1.1 403 Forbidden');
        exit;
//        $ip = is_null($ip) ? request()->ip() : $ip;
//        $forbiddenipArr = config('site.forbiddenip');
//        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
//        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
//        if ($forbiddenipArr && !in_array($ip, $forbiddenipArr)) {
//            header('HTTP/1.1 403 Forbidden');
//            exit;
//        }
    }
}

if (!function_exists('admin_check_ip_allowed')) {
    /**
     * 检测超级管理员ip是否允许
     * @param string $ip IP地址
     */
    function admin_check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;

//        $configInfo = \app\admin\model\SysConfig::get(1);
//        $configInfo = json_decode($configInfo['according'], true);
//        //该字段为空则代表所有ip均允许通过
//        if (empty($configInfo['forbidden_ip'])) {
//            return true;
//        }
//        $forbiddenIps = explode(',', $configInfo['forbidden_ip']);
        $forbiddenIps = \app\admin\model\SysForbiddenIp::field('ip')
            ->where([
                'status' => 1,
                'ip_group_id' => 10
            ])
            ->select()
            ->toArray();
        $forbiddenIps = array_column($forbiddenIps, 'ip');
        if (in_array($ip, $forbiddenIps)) {
            return true;
        }
//        if (is_array($forbiddenIps)) {
//            //去除两侧多余字符
//            foreach ($forbiddenIps as $key => $value) {
//                $forbiddenIps[$key] = trim($value);
//            }
//            if (in_array($ip, $forbiddenIps)) {
//                return true;
//            }
//        }
        header('HTTP/1.1 403 Forbidden');
        exit;
//        $ip = is_null($ip) ? request()->ip() : $ip;
//        $forbiddenipArr = config('site.forbiddenip');
//        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
//        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
//        if ($forbiddenipArr && !in_array($ip, $forbiddenipArr)) {
//            header('HTTP/1.1 403 Forbidden');
//            exit;
//        }
    }
}
if (!function_exists('create_order_number')) {
    /**
     * 生成订单号
     */
    function create_order_number()
    {
        $str = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        return $str;
    }
}


if (!function_exists('yang_numberRand')) {
    /**
     * 获取一定范围内的多个随机数字
     */
    function yang_numberRand($begin, $end, $limit)
    {
        $rand_array = range($begin, $end);
        shuffle($rand_array); //调用现成的数组随机排列函数
        return array_slice($rand_array, 0, $limit); //截取前$limit个
    }
}


if (!function_exists('str_change')) {
    /**
     * 字符串随机位数对调
     */
    function str_change($str, $try_num = 0)
    {
        $strl = strlen($str);
        $start = rand(1, $strl - 1);
        $str1 = substr($str, $start, 1);
        $str2 = substr($str, $start - 1, 1);
        $stra = substr_replace($str, $str2, $start, 1);
        $strb = substr_replace($stra, $str1, $start - 1, 1);
        if ($strb == $str) {
            if ($try_num < 4) {
                $strb = str_change($str, $try_num + 1);
            } elseif ($try_num == 4) {
                $s = rand(0, 9);
                $strb = substr_replace($strb, $s, rand(1, $strl), 1);
                if ($strb == $str) {
                    $strb = str_change($str, $try_num);
                }
            }
        }
        return $strb;
    }
}


if (!function_exists('random_str')) {
    /**
     *  生成随机字符串
     *
     *   $length    字符串长度
     */
    function random_str($length)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}

/**
 * 二维数组内进行模糊搜索
 * @param array $array 需要检索的数组
 * @param string $key 需要检索的key的值（为空则检索所有key的值）
 * @param string $search 搜索的关键词
 * @return array
 */
if (!function_exists('search_array_by_key')) {
    function search_array_by_key($array, $search, $key = '')
    {
        $arr = $result = array();
        foreach ($array as $k => $v) {

            if (empty($key)) {
                foreach ($v as $val) {
                    if (strstr($val, $search) !== false) {
                        array_push($arr, $k);
                    }
                }
            } else {
                if (strstr($v[$key], $search) !== false) {
                    array_push($arr, $k);
                }
            }

        }
        foreach ($arr as $k => $v) {
            if (array_key_exists($v, $array)) {
                array_push($result, $array[$v]);
            }
        }
        return $result;
    }
}


/**
 * 生成唯一订单号
 * @param string $prefix 是否加前缀
 * @return string
 */
if (!function_exists('createTradeNo')) {
    function createTradeNo($prefix = '')
    {
        return $prefix . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
    }
}

/**
 * 二维数组根据字段进行排序
 * @params array $array 需要排序的数组
 * @params string $field 排序的字段
 * @params string $sort 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
 */
if (!function_exists('arraySequence')) {
    function arraySequence($array, $field, $sort = 'SORT_ASC')
    {
        if (empty($array)) {
            return $array;
        }
        $arrSort = array();
        foreach ($array as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$field], constant($sort), $array);
        return $array;
    }
}

/**
 * 输出两个日期之间的所有日期
 */
if (!function_exists('printDates')) {
    function printDates($start, $end)
    {
        $dt_start = strtotime($start);
        $dt_end = strtotime($end);
        $dateList = [];
        while ($dt_start <= $dt_end) {
            $dateInfo['date'] = date('Y-m-d', $dt_start);
            $dateInfo['start_time'] = strtotime(date('Y-m-d', $dt_start) . '00:00:00');//开始时间
            $dateInfo['end_time'] = strtotime(date('Y-m-d', $dt_start) . '23:59:59');//结束时间
            $dateList[] = $dateInfo;
            $dt_start = strtotime('+1 day', $dt_start);
        }
        return $dateList;
    }
}
/**
 * 时区转换 IND 印度  MX 墨西哥
 */
if (!function_exists('timeZoneConvert')) {
    function timeZoneConvert($zone = '1')
    {
        $time = time();
        //时区配置  IND 印度  MX 墨西哥
        $zoneArr = [
            '1' => [
                'type' => 'increase',
                'diff' => 0
            ],
            '20' => [
                'type' => 'reduce',
                'diff' => 36000
            ]
        ];
        if (empty($zoneArr[$zone])) {
            return $time;
        }
        if ($zoneArr[$zone]['type'] == 'increase') {
            $time = $time + $zoneArr[$zone]['diff'];
        } elseif ($zoneArr[$zone]['type'] == 'reduce') {
            $time = $time - $zoneArr[$zone]['diff'];
        }
        return $time;
    }
}
/**
 * 汇率转换
 */
if (!function_exists('exchangeRateConversion')) {
    function exchangeRateConversion($InMoney)
    {
        if (empty($InMoney)) {
            return 0;
        }
        $exchange = 0.88;
        $rmb = $InMoney * $exchange;
        $rmb = $rmb / 100;
        return $rmb * 6.5;
    }
}
if (!function_exists('request_post')) {
    function request_post($url = '', $data = '')
    {

        $postData = http_build_query($data);

        $ch = curl_init();

        // 设置选项，包括URL

        curl_setopt($ch, CURLOPT_URL, $url);

        $header = array();

        $header [] = 'User-Agent: ozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1';

        $header [] = 'Accept-Charset: UTF-8,utf-8;q=0.7,*;q=0.3';

        $header [] = 'Content-Type:application/x-www-form-urlencoded';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);    // 对证书来源的检查

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);    // 从证书中检查SSL加密算法是否存在

        //        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    // 使用自动跳转

        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);       // 自动设置Referer

        curl_setopt($ch, CURLOPT_POST, 1);      // 发送一个 常规的Post请求

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);    // Post提交的数据包

        curl_setopt($ch, CURLOPT_TIMEOUT, 30);      // 设置超时限制防止死循环

        curl_setopt($ch, CURLOPT_HEADER, 0);        // 显示返回的Header区域内容

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    //获取的信息以文件流的形式返回


        $output = curl_exec($ch);

        if (curl_errno($ch)) {

            echo "Errno" . curl_error($ch);   // 捕抓异常

        }

        curl_close($ch);    // 关闭CURL

        return $output;

    }
}

function calculateExactAge($birthdate) {
    $birthdate = strtotime($birthdate);
    $today = strtotime("today");
    $age = date("Y", $today) - date("Y", $birthdate);

    // 检查是否已过今年的生日
    if (date("md", $today) < date("md", $birthdate)) {
        $age--;
    }
    if ($age == 0) {
        $age = 1;
    }

    return $age;
}


function getHeader($name, $default = null)
{

    return isset($_SERVER['HTTP_' . strtoupper(str_replace('-', '_', $name))]) ? $_SERVER['HTTP_' . strtoupper(str_replace('-', '_', $name))]:  $default;
}

function getRealClientIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        // 检查是否为私有IP
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // 取第一个非私有IP
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        foreach ($ips as $ip) {
            $ip = trim($ip);
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                break;
            }
        }
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }


    return $ip;
}


